<template>
  <div ref="chart" style="width: 100%; height: 100%;"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'LineChart',
  props: {
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['预期', '实际']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '预期',
            type: 'line',
            stack: '总量',
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(58, 77, 233, 0.8)'
                },
                {
                  offset: 1,
                  color: 'rgba(58, 77, 233, 0.1)'
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: this.chartData.expectedData
          },
          {
            name: '实际',
            type: 'line',
            stack: '总量',
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(64, 158, 255, 0.8)'
                },
                {
                  offset: 1,
                  color: 'rgba(64, 158, 255, 0.1)'
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: this.chartData.actualData
          }
        ]
      }
      this.chart.setOption(option)
      window.addEventListener('resize', this.resizeHandler)
    },
    resizeHandler() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        if (this.chart) {
          this.chart.setOption({
            series: [
              {
                data: this.chartData.expectedData
              },
              {
                data: this.chartData.actualData
              }
            ]
          })
        }
      }
    }
  }
}
</script>